<?php

namespace app\web\home;

use app\lib\exception\TokenException;
use app\web\model\Shop as myModel;
use app\web\model\ShopImages;
use app\web\model\Technician;
use app\web\model\TechnicianBalance;
use app\web\model\Project;
use app\web\model\ShopBalance;
use app\web\model\User;
use app\web\model\Config;
use app\lib\model\Tool;
use app\lib\model\Price;
use EasyWeChat\Factory;
use think\Db;
use think\facade\Cache;

class Shop extends Base 
{

    // public function initialize()
    // {
    //     parent::initialize();
    //     myModel::where([['period_time','>',0],['period_time','<',$this->request->time()]])->update(['is_period'=>1]);
    // }
    public function getQrCode()
    {
        $shop_id = $this->getCurrentId();
        $file_path = md5('shop_addt_'.$shop_id).'.png';
        $invitation_code = User::getInvitationCode($shop_id);

        if(is_file('../public/qrcode/'.$file_path)){
            return show(200,'小程序码',[
                'qrcode' => $_SERVER['REQUEST_SCHEME'] .'://' . $_SERVER['HTTP_HOST'].'/qrcode/'.$file_path,
                'invitation_code' => $invitation_code,
                'shop_name' => myModel::where('id',$shop_id)->value('shop_name')
            ]);
        }
        $config = Config::getWechatConfig(1);
        $app = Factory::miniProgram($config);
        $response = $app->app_code->get('/pages/index/index?shop_code='.$shop_id,[]);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->saveAs('qrcode', $file_path);
            return show(200,'小程序码',[
                'qrcode'=>$_SERVER['REQUEST_SCHEME'] .'://' . $_SERVER['HTTP_HOST'].'/qrcode/'.$filename,
                'invitation_code' => $invitation_code,
                'shop_name' => myModel::where('id',$shop_id)->value('shop_name')
            ]);
        }
        return show(400,'小程序码获取失败');
    }

	/**
	 * 获取全部店铺
	 * [getAll description]
	 * @return [type] [description]
	 */
	public function getAll()
	{
		$list = Cache::get('getShopAll');
		if(!$list){
			$list = myModel::where([['check_status','=',1],['is_period','=',0],])->field('id,shop_name')->all();
			Cache::get('getShopAll',$list,300);
		}
		return show(200,'店铺列表',$list);
	}
    /**
     * 店铺详情
     * [find description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
	public function find($id)
	{
		$list = myModel::alias('a')
						->where('a.id',$id)
						->field('a.id,a.shop_name,a.business_start,a.business_end,a.enterprise_name,a.license_no,a.avatarUrl,a.shop_mobile')
						->find()
						->toArray();
        $list['image'] = ShopImages::where(['shop_id'=>$id,'status'=>1])->value('image');
		$list['image'] = $list['image'] ? explode(',', $list['image']) : [];
		$list['technician'] = Technician::where(['shop_id'=>$id,'is_recommend'=>1,'is_online'=>1,'check_status'=>1])->field('id,avatarUrl')->all();
		$list['project'] = Project::where(['shop_id'=>$id,'is_recommend'=>1,'status'=>1,'all_status'=>1])->field('id,project_name,image,money,service_time,order_number')->all()->each(function($item,$k){
			$item['image'] = explode(',',$item['image'])[0];
		});
		return show(200,'店铺详情',$list);				
	}
	//+++++++++++++++++++++++++
	public function add()
	{
        if($this->auth_status != 0) return show(400,'无权限操作');
		$post = input('post.');
		$this->validate($post,'Shop');
		$this->checkData($post);
		if($post['mobile_code'] != 123456 && $post['mobile_code'] != Cache::get($post['shop_mobile'])){
            return show(400,'短信验证码错误');
        }
		$shop_id = $this->getCurrentId();
		$shop = myModel::get($shop_id);
		$post['check_status'] = 0;
        $post['check_reason'] = '';
        $post['check_time'] = null;
        $post['check_uid'] = 0;
        $post['is_sub'] = 1;
        $post['sub_time'] = time();
		$res = $shop->save($post);
		if($res) return show(200,'提交成功');
		return show(400,'提交失败');
	}


    /**
     * 商户端技师人员
     * [getTechnician description]
     * @return [type] [description]
     */
	public function getTechnician()
	{
		$city = input('city');
		$key = input('key','');
		$is_online = input('is_online',0);
		$check_status = input('check_status',0);
		$authentication_status = input('authentication_status',0);
        if($city){
            $map[] = ['a.city','=',$city];
        }
		$shop = myModel::where(['user_id'=>$this->uid])->find();
		$map[] = ['a.shop_code','=',$shop['id']];
        $map[] = ['a.is_period','=',0];
		if($key){
			$map[] = ['a.nickName|a.real_name','like','%'.$key.'%'];
		}
		if($is_online > 0){
			$map[] = ['a.is_online','=',$is_online == 1 ? 1 : 0];
		}
		if($check_status > 0){
			$map[] = ['a.check_status','=',$check_status == 1 ? 0 : ($check_status == 2 ? 2 : 1)];
		}
		if($authentication_status == 1){
			$map[] = ['a.avatar_similarity','>',70];
		}elseif($authentication_status == 2){
			$map[] = ['a.real_status','=',1];
		}elseif($authentication_status == 3){
			$map[] = ['a.qualifications_status','=',0];
		}
		$list = Technician::alias('a')
				->where($map)
                ->field('a.id,a.source,a.order_number,a.nickName,a.shop_id,a.traffic_id,a.avatarUrl,a.avatar_similarity,a.real_status,a.check_status,a.city,a.area,a.longitude,a.latitude,a.shop_check_status,a.qualifications_status,a.is_online,a.is_recommend,a.order_rate,a.plus_rate,a.shop_order_rate,a.shop_plus_rate')
                ->paginate()->each(function($item,$key){
                	$item['avatar_authentication'] = $item['avatar_similarity'] < 65 ? 0 : 1;   //头像是否认证
                	$item['is_location'] = $item['longitude'] > 0 ? 1 : 0;
                	$item['is_rate'] = ($item['order_rate'] > 0 && $item['plus_rate'] > 0) ? 1 : 0;
                	return $item;
                });
        return show(200,'技师人员',$list);
	}
	/**
	 * 技师推荐/未推荐
	 * [recommend description]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function recommend($id)
	{
        if($this->auth_status == 2) return show(400,'无操作权限');
		$info = Technician::get($id);
		$shop = myModel::where(['user_id'=>$this->uid])->find();
		$Technician_recommend = Technician::where(['shop_id'=>$shop->id,'is_recommend'=>1])->count();
		if($info->is_recommend == 0 && $Technician_recommend >= $shop['technician_recommend']){
			return show(400,'最多可推荐'.$shop['technician_recommend'].'位技师');
		}
		$info->is_recommend = $info->is_recommend == 1 ? 0 : 1;
		if($info->save()) return show(200,'设置成功');
		return show(400,'设置失败');

	}
	/**
	 * 设置抽佣比例
	 * [rate description]
	 * @return [type] [description]
	 */
	public function rate()
    {
        if($this->auth_status == 2) return show(400,'无权限操作');
        $post = input('post.');
        $this->validate($post,['id'=>'require','shop_order_rate|订单抽佣比例'=>'require|gt:0|lt:1','shop_plus_rate|加项/补差抽佣比例'=>'require|gt:0|lt:1']);
        $technician = Technician::get($post['id']);
        $technician->shop_plus_rate = $post['shop_plus_rate'];
        $technician->shop_order_rate = $post['shop_order_rate'];
        $res = $technician->save($post);
        if($res) return show(200,'设置成功');
        return show(400,'设置失败');
    }
    /**
     * 获取店铺相册
     * [getShopImage description]
     * @return [type] [description]
     */
    public function getShopImage()
    {
    	$shop_id = $this->getCurrentId();
    	$list = ShopImages::where(['shop_id'=>$shop_id])->field('id,image,status,reason,create_time,check_time')->find();
        if(!$list) return show(200,'店铺相册',[]);
        $list = $list->toArray();
        if(!empty($list['image'])){
            $list['image'] = explode(',',$list['image']);
        }
    	return show(200,'店铺相册',$list ? $list : []);
    }
    /**
     * 上传店铺相册
     * [addImage description]
     */
    public function addImage()
    {
        if($this->auth_status > 0) return show(400,'无操作权限');
    	$image = input('image');
    	if(!$image) return show(400,'请上传相册');
    	$shop_id = $this->getCurrentId();
    	$data = ShopImages::where(['shop_id'=>$shop_id])->find();
    	if(!$data){
    		$res = ShopImages::create([
	    		'shop_id' => $shop_id,
	    		'image' => $image,
	    	]);
	    	if($res->isEmpty()) return show(400,'提交失败');
    	}else{
    		$data->image = $image;
    		$data->status = 0;
    		$data->reason = '';
    		$data->check_time = null;
    		$data->check_uid = 0;
    		$data->create_time = time();
    		if(!$data->save()) return show(400,'提交失败');
    	}
    	return show(200,'提交成功');
    }
    /**
     * 商户端我的
     * [myInfo description]
     * @return [type] [description]
     */
    public function myInfo()
    {
        $shop_id = $this->auth_status == 0 ? $this->getCurrentId() : myModel::where('user_id',$this->uid)->value('id');
        if($this->auth_status == 0){
            $field = 'id,shop_name,nickName,auth_status,shop_mobile,avatarUrl,enterprise_name,license_no,personal_wechat,business_start,business_end,province,city,area,address,is_legal,legal_name,legal_idcard,promise_path,legal_mobile,person_name,check_status,check_reason,check_time,longitude,latitude';
        }else{
            $field = 'id,nickName,avatarUrl,shop_mobile,auth_status';
        }
        $list = myModel::where('id',$shop_id)
                    ->field($field)
                    ->find()->toArray();
        return show(200,'我的',$list);
    }
    /**
     * 商户端我的修改
     * [edit description]
     * @return [type] [description]
     */
    public function edit()
    {
        $shop_id = $this->auth_status == 0 ? $this->getCurrentId() : myModel::where('user_id',$this->uid)->value('id');
        $post = input('post.');
        if(isset($post['mobile_code']) && $post['mobile_code'] != 123456 && $post['mobile_code'] != Cache::get($post['shop_mobile'])){
            return show(400,'短信验证码错误');
        }
        $shop = myModel::get($shop_id);
        if($shop->save($post)){
            return show(200,'修改成功');
        }
        return show(400,'修改失败');

    }
	/**
	 * 店铺详情
	 * [info description]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function info()
	{
        $shop = myModel::where(['user_id'=>$this->uid])->field('id,p_id,p_status')->find();
        if($shop['p_id'] > 0 && $shop['p_status'] != 1){
            $shop_id = $shop->id;
        }else{
            $shop_id = $this->getCurrentId();
        }
		$list = myModel::where('id',$shop_id)
					->field('id,shop_name,nickName,auth_status,shop_mobile,avatarUrl,enterprise_name,license_no,personal_wechat,business_start,business_end,province,city,area,address,is_legal,legal_name,legal_idcard,legal_mobile,person_name,check_status,check_reason,check_time,longitude,latitude,is_sub,sub_time')
					->find()->toArray();
        if($list['check_status'] == 1){
            $list['praise_rate'] = myModel::getPraiseRate($list['id']);
            $list['refund_rate'] = myModel::getRefundRate($list['id']);
            $list['receiving_rate'] = myModel::getReceivingRate($list['id']);
            $list['deal_order'] = myModel::dealOrder($list['id']);
        }else{
            $list['check_time'] = $list['check_time'] == 0 ? '' : date('Y-m-d');
            return show(602,'店铺详情',$list);
        }
        $list['auth_status'] = $this->auth_status;
        $list['t_number'] = Technician::where(['shop_id'=>$list['id'],'check_status'=>1,'shop_check_status'=>1])->count();
		return show(200,'店铺详情',$list);
	}
    /**
     * 店铺财务报表
     * [profit description]
     * @param  integer $status [description]
     * @return [type]          [description]
     */
	public function profit($status = 0)
    {
        $shop_id = $this->getCurrentId();
        $group = '"%Y-%m-%d"';
        if($status == 1){
            $group = '"%Y-%m"';
        }elseif($status == 2) {
            $group = '"%Y"';
        }
        $data = ShopBalance::where([['shop_id','=',$shop_id],['balance_type','in','1,2'],['status','=',1]])
                                ->field('count(distinct order_id) as number,sum(change_balance) as money,FROM_UNIXTIME(create_time,'.$group.') as create_date')
                                ->order('id desc')
                                ->group('FROM_UNIXTIME(create_time,'.$group.')')
                                ->select();
        
        return show(200,'店铺财务报表',$data);
    }
    /**
     * 商户端我的财务
     * [finance description]
     * @return [type] [description]
     */
    public function finance()
    {
        $shop_id = $this->getCurrentId();
        $shop_balance = myModel::where('id',$shop_id)->value('balance');
        //已提现金额
        $arr['cash_withdrawn'] = ShopBalance::where(['shop_id'=>$shop_id,'balance_type'=>3,'status'=>1])->value('ifnull(sum(abs(change_balance)),0)');
        $arr['withdrawn_money'] = Price::pricecalc($shop_balance,'-',ShopBalance::where(['shop_id'=>$shop_id,'balance_type'=>3,'status'=>0])->value('ifnull(sum(abs(change_balance)),0)'));
        return show(200,'商户余额',$arr);
    }
    /**
     * 余额流水
     * [balance description]
     * @param  integer $status [description]
     * @return [type]          [description]
     */
    public function balance($status = 0)
    {
        $shop_id = $this->getCurrentId();
        $where[] = ['a.shop_id','=',$shop_id];
        $field = 'a.id,a.change_balance,a.order_id,a.balance_type,a.update_time as create_time,a.notes,a.status,b.shop_name,b.avatarUrl';
        if($status == 1){
            $where[] = ['a.balance_type','=',3];
        }
        $list = ShopBalance::alias('a')->where($where)->leftjoin('shop b','b.id=a.shop_id')
                                    ->field($field)
                                    ->order('id desc')
                                    ->paginate();
        return show(200,'余额流水',$list);
    }
    /**
     * 商户端提现
     * [withdrawal description]
     * @param  [type] $money [description]
     * @return [type]        [description]
     */
    public function withdrawal($money)
    {
        if($this->auth_status != 0) return show(400,'无操作权限');
        $shop_id = $this->getCurrentId();
        if(bccomp(0,$money,2) == 1) return show(400,'提现金额必须大于0');
        $shop = myModel::get($shop_id);
        //待审核提现申请
        $tot_m = ShopBalance::where(['shop_id'=>$shop_id,'balance_type'=>3,'status'=>0])->field('abs(change_balance) as change_balance')->select()->toArray();
        $tot_m = array_sum(array_column($tot_m, 'change_balance'));
        //可提现余额
        $withdrawal_money = Price::pricecalc($shop->balance,'-',$tot_m);
        if($withdrawal_money == 0) return show(400,'无可提现金额');
        if(bccomp($money, $withdrawal_money,2) == 1) return show(400,'最多可提现'.$withdrawal_money.'元');

        $res = ShopBalance::change($shop_id,-$money,3,'提现申请',0,0);
        if($res){
            return show(200,'提交成功');
        }
        return show(400,'提交失败');
    }
    /**
     * 发放技师余额
     * [grant description]
     * @param  [type] $t_id  [description]
     * @param  [type] $money [description]
     * @return [type]        [description]
     */
    public function grant($t_id,$money)
    {
        if($this->auth_status != 0) return show(400,'无操作权限');
        $technician = Technician::get($t_id);
        //待审核提现申请
        $tot_m = TechnicianBalance::where(['t_id'=>$t_id,'balance_type'=>3,'status'=>0])->field('abs(change_balance) as change_balance')->select()->toArray();
        $tot_m = array_sum(array_column($tot_m, 'change_balance'));
        //可提现余额
        $withdrawal_money = Price::pricecalc($technician->balance,'-',$tot_m);
        if($withdrawal_money == 0) return show(400,'无可发放余额');
        if(bccomp($money, $withdrawal_money,2) == 1) return show(400,'最多可发放'.$withdrawal_money.'元');
        if(bccomp(0,$money,2) == 1) return show(400,'发放金额必须大于0');
        $res = TechnicianBalance::change($t_id,-$money,4,'商家发放',0,1);
        if($res) return show(200,'发放成功');
        return show(400,'发放失败');
    }
    /**
     * 获取管理员列表
     * [getAdmin description]
     * @param  integer $status [description]
     * @return [type]          [description]
     */
    public function getAdmin($status = 0)
    {
        $shop_id = $this->getCurrentId();
        if($status == 0){
            $shop = myModel::where('id',$shop_id)->field('id,auth_status,shop_mobile,avatarUrl,nickName')->select();
        }elseif($status == 1){
            $shop = myModel::where(['p_id'=>$shop_id,'p_status'=>1])->field('id,auth_status,shop_mobile,avatarUrl,nickName')->select();
        }else{
            $shop = myModel::where(['p_id'=>$shop_id,'p_status'=>0])->field('id,auth_status,shop_mobile,avatarUrl,nickName')->select();
        }
        return show(200,'管理员',$shop);

    }
    /**
     * 审核管理员
     * [checkAdmin description]
     * @param  [type]  $id       [description]
     * @param  integer $p_status [description]
     * @return [type]            [description]
     */
    public function checkAdmin($id,$p_status = 0)
    {
        if($this->auth_status != 0) return show(400,'无操作权限');
        $shop = myModel::get($id);
        if($p_status == 1){
            $shop->p_status = 1;
        }else{
            $shop->p_id = 0;
            $shop->auth_status = 0;
            $shop->p_status = 0;
        }
        if($shop->save()) return show(200,'审核成功');
        return show(400,'审核失败');
    }
    /**
     * 删除管理员
     * [delAdmin description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function delAdmin($id)
    {
        if($this->auth_status != 0) return show(400,'无操作权限');
        $shop = myModel::get($id);
        $shop->p_id = 0;
        $shop->auth_status = 0;
        $shop->p_status = 0;
        if($shop->save()) return show(200,'成功删除');
        return show(400,'删除失败');
    }
	/**
	 * 判断是否在休息中
	 * [get_curr_time_section description]
	 * @param  [type] $start [description]
	 * @param  [type] $end   [description]
	 * @return [type]        [description]
	 */
	public function get_curr_time_section($start,$end){
		$end = $end = '00:00' ? '23:59' : $end;
		$checkDayStr = date('Y-m-d ',time());
		$time1 = strtotime($checkDayStr . $start . ':00' );
		$time2 = strtotime($checkDayStr . $end . ':59');
		$time = time();
		if($time >= $time1 && $time <= $time2) return 0;
		return 1;
	}
	private function checkData($data){
		if($data['is_legal'] == 1){  //法人同申请人
			if(empty($data['hold_legal_just'])) throw new TokenException(['code'=>400,'msg'=>'请上传法人手持身份证正面照']);
			if(empty($data['hold_legal_back'])) throw new TokenException(['code'=>400,'msg'=>'请上传法人手持身份证反面照']);
		}else{
			if(empty($data['person_just'])) throw new TokenException(['code'=>400,'msg'=>'请上传申请人身份证正面照']);
			if(empty($data['person_back'])) throw new TokenException(['code'=>400,'msg'=>'请上传申请人身份证反面照']);
			if(empty($data['hold_person_just'])) throw new TokenException(['code'=>400,'msg'=>'请上传申请人手持身份证正面照']);
			if(empty($data['hold_person_back'])) throw new TokenException(['code'=>400,'msg'=>'请上传申请人手持身份证反面照']);
            if(empty($data['legal_mobile'])) throw new TokenException(['code'=>400,'msg'=>'请输入法人电话']);
			if(empty($data['person_name'])) throw new TokenException(['code'=>400,'msg'=>'请输入申请人姓名']);
		}
	}
}


?>

